//
//  XUITableView.m
//  Etion
//
//  Created by JingXing Wu on 11-11-9.
//  Copyright (c) 2011年 GuangZhouXuanWu. All rights reserved.
//

#import "XUITableView.h"

#import "UIStyleSkinManager.h"

#import "UIStyleSkinManagerInternal.h"

@interface XUITableView ()
{
    UITableViewCell *_showmenucell;
    
    NSMutableDictionary *_sectionRowHeight;
}
@end

@implementation XUITableView

@synthesize refreshHeaderView = _refreshHeaderView;
@synthesize searchBar = _searchBar;
@synthesize dicCellhead = _dicCellhead;
@synthesize loadMoreView = _loadMoreView;
@dynamic delegate;

- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style
{
    [super initWithFrame:frame style:style];
    
    self.backgroundColor = [[UITableView appearance] backgroundColor];
    //    self.separatorColor = TABLESEPERATORCOLOR;
    self.rowHeight = CUSTOMBASETABELVIEWCELLHEIGHT;
    
    _dicCellhead = [NSMutableDictionary new];
    
    if ([self respondsToSelector:@selector(cellLayoutMarginsFollowReadableWidth:)])
    {
        [self setCellLayoutMarginsFollowReadableWidth:NO];
    }
    if ([self respondsToSelector:@selector(setSeparatorInset:)])
    {
        [self setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self setLayoutMargins:UIEdgeInsetsZero];
    }
    
    return self;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    if(_refreshHeaderView.hiddenTitle == NO)
    {
        id date = [self refreshHeaderViewLastUpdateTime:_refreshHeaderView];
        [_refreshHeaderView setLastUpdateTime:date];
    }
}

-(void)setSeparatorExistFollowCell:(BOOL)separatorExistFollowCell
{
    _separatorExistFollowCell = separatorExistFollowCell;
    
    if(separatorExistFollowCell == YES)
    {
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    else
    {
        self.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }
}

-(id<XUITableViewDelegate>)delegate
{
    return (id<XUITableViewDelegate>)super.delegate;
}

- (void)createRefreshHead
{
    if(_refreshHeaderView == nil)
        _refreshHeaderView = [[XUIRefreshHeaderView alloc]initWithDelegate:self];
    
    [self addSubview:_refreshHeaderView];
}

- (void)removeRefreshHead
{
    [_refreshHeaderView removeFromSuperview];
}

- (void)createSearchBar
{
    CGFloat searchBarW = self.width;
    if ([self.dataSource respondsToSelector:@selector(sectionIndexTitlesForTableView:)])
    {
        if ([self.dataSource sectionIndexTitlesForTableView:self].count > 0)
        {
            if ([[UIDevice currentDevice].systemVersion integerValue] >= 7)
            {
                searchBarW -= 15;
            }
            else
            {
                searchBarW -= 25;
            }
        }
    }
    _searchBar = [[XUISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.width, 44) styleType:XUISearchBarStyleTypeDefault customAreaWidth:searchBarW];
    _searchBar.backgroundimage = [UIImage imageNamed:@"tableviewheaderbg.png"];
    self.tableHeaderView = _searchBar;
}

- (void)createLoadMoreView
{
    if(_loadMoreView == nil)
        _loadMoreView = [[XUILoadMoreFootView alloc] initWithFrame:CGRectMake(0, 0, self.width, 32) delegate:self];
    
    self.tableFooterView = _loadMoreView;
}

- (void)removeLoadMoreView
{
    self.tableFooterView = nil;
    [_loadMoreView removeFromSuperview];
    ReleaseObj(_loadMoreView);
}

- (void)refreshHeaderViewBeginRefreshing:(XUIRefreshHeaderView *)view
{
    void(^f)()=^()
    {
        DispatchMainThreadAsync(^{
            
            [_refreshHeaderView endRefreshing];
        });
    };
    
    if ([self.delegate respondsToSelector:@selector(tableView:refreshTableContent:)])
        [self.delegate tableView:self refreshTableContent:f];
}

- (id)refreshHeaderViewLastUpdateTime:(XUIRefreshHeaderView *)view
{
    id date = nil;
    if ([self.delegate respondsToSelector:@selector(contentLastRefreshUpdateTimeOfTableView:)])
        date = [self.delegate contentLastRefreshUpdateTimeOfTableView:self];
    return date;
}

- (void)showRefreshView
{
    [_refreshHeaderView showRefreshing];
}

- (void)hideRefreshView
{
    [_refreshHeaderView endRefreshing];
}

- (void)selectRowAtIndexPath:(NSIndexPath *)indexpath
{
    [self selectRowAtIndexPath:indexpath animated:YES scrollPosition:UITableViewScrollPositionNone];
}

- (void)deselectRowAtIndexPath:(NSIndexPath *)indexpath
{
    if (indexpath == nil)
        indexpath = [self indexPathForSelectedRow];
    if (indexpath != nil)
        [self deselectRowAtIndexPath:indexpath animated:YES];
}

- (void)loadMoreRefreshScrollViewDidEndDragging:(UIScrollView *)scrollview
{
    if ([self.delegate respondsToSelector:@selector(loadMoreContentOfTableView:)])
        [self.delegate loadMoreContentOfTableView:self];
}

- (BOOL)loadMoreRefreshScrollViewIsLoading:(UIScrollView *)scrollview
{
    BOOL bResult = NO;
    if ([self.delegate respondsToSelector:@selector(loadingMoreContentOfTableView:)] == YES)
        bResult = [self.delegate loadingMoreContentOfTableView:self];
    return bResult;
}

- (void)clickedLoadMoreFootView:(XUILoadMoreFootView *)sender
{
    if ([self.delegate respondsToSelector:@selector(tableView:didClickedLoadMoreFootView:)])
        [self.delegate tableView:self didClickedLoadMoreFootView:sender];
}

- (void)loadMoreViewRefreshScrollViewDidScroll:(UIScrollView *)scrollView
{
    [_loadMoreView loadMoreRefreshScrollViewDidScroll:scrollView];
}

- (void)loadMoreViewRefreshScrollViewDidEndDragging:(UIScrollView *)scrollView
{
    [_loadMoreView loadMoreRefreshScrollViewDidEndDragging:scrollView];
}

- (void)showLoadMoreStatus
{
    [_loadMoreView loadMoreRefreshScrollViewDidLoading];
}

- (void)hideLoadMoreStatus
{
    [_loadMoreView loadMoreRefreshScrollViewDidFinishLoading];
}

- (void)reloadData
{
    if(_searchBar != nil)
    {
        CGFloat searchBarW = self.width;
        if ([self.dataSource respondsToSelector:@selector(sectionIndexTitlesForTableView:)])
        {
            if ([self.dataSource sectionIndexTitlesForTableView:self].count > 0)
            {
                if ([[UIDevice currentDevice].systemVersion integerValue] >= 7)
                {
                    searchBarW -= 15;
                }
                else
                {
                    searchBarW -= 25;
                }
            }
        }
        _searchBar.customAreaW = searchBarW;
    }
    [_sectionRowHeight removeAllObjects];
    [super reloadData];
}

-(void)showMenuAtCell:(XUITableViewCell*)cell
{
    if(_showmenucell!=nil)
    {
        [self resignFirstResponderMenuAtCell];
        return;
    }
    
    if(cell==nil)
        return;
    
    _showmenucell=[cell retain_mm];
    
    NSArray *arMenuitem=[cell menuItem];
    if(arMenuitem.count<=0)
        return;
    CGRect menuFrame=[cell menuFrame];
    if(CGRectEqualToRect(menuFrame,CGRectZero)==YES)
        return;
    
    [_showmenucell becomeFirstResponder];
    
    UIMenuController *menu = [UIMenuController sharedMenuController];
    [menu setMenuItems:arMenuitem];
    [menu setTargetRect:menuFrame inView:self];
    [menu setMenuVisible:YES animated:YES];
}

-(void)resignFirstResponderMenuAtCell
{
    if(_showmenucell!=nil)
    {
        UIMenuController *menu=[UIMenuController sharedMenuController];
        [menu setMenuVisible:NO animated:YES];
        [_showmenucell resignFirstResponder];
        ReleaseObj(_showmenucell);
    }
}

-(XUITableViewCell*)findVisibleCellWithTag:(NSString*)szTag
{
    for(XUITableViewCell *cell in [self visibleCells])
    {
        if([cell.szTag isEqualToString:szTag])
            return cell;
    }
    return nil;
}

-(void)setHeight:(CGFloat)height forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(_sectionRowHeight == nil)
        _sectionRowHeight = [NSMutableDictionary new];
    
    NSMutableDictionary *row = _sectionRowHeight[@(indexPath.section)];
    if(row == nil)
    {
        row = [[NSMutableDictionary new] autorelease_mm];
        _sectionRowHeight[@(indexPath.section)] = row;
    }
    
    row[@(indexPath.row)] = @(height);
}

-(CGFloat)heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *row = _sectionRowHeight[@(indexPath.section)];
    NSNumber *height = row[@(indexPath.row)];
    if(height == nil)
        return -1;
    return [height floatValue];
}

-(void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
{
    [super insertRowsAtIndexPaths:indexPaths withRowAnimation:animation];
}

-(void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
{
    if(_sectionRowHeight.count > 0)
    {
        for(NSIndexPath *indexPath in indexPaths)
        {
            NSMutableDictionary *row = _sectionRowHeight[@(indexPath.section)];
            [row removeObjectForKey:@(indexPath.row)];
        }
        
        NSMutableSet *set = [[NSMutableSet new] autorelease_mm];
        for(NSIndexPath *indexPath in indexPaths)
        {
            [set addObject:@(indexPath.section)];
        }
        
        for(NSNumber *section in [set allObjects])
        {
            NSMutableDictionary *n = [[NSMutableDictionary new] autorelease_mm];
            NSMutableDictionary *row = _sectionRowHeight[section];
            [[row allKeys] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
            {
                n[@(idx)] = row[obj];
            }];
        }
    }
    
    [super deleteRowsAtIndexPaths:indexPaths withRowAnimation:animation];
}

-(void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
{
    if(_sectionRowHeight.count > 0)
    {
        for(NSIndexPath *indexPath in indexPaths)
        {
            NSMutableDictionary *row = _sectionRowHeight[@(indexPath.section)];
            [row removeObjectForKey:@(indexPath.row)];
        }
    }
    
    [super reloadRowsAtIndexPaths:indexPaths withRowAnimation:animation];
}

- (void)dealloc
{
    [_sectionRowHeight release_mm];
    [_showmenucell release_mm];
    [_dicCellhead release_mm];
    [_loadMoreView release_mm];
    [_searchBar release_mm];
    [_refreshHeaderView release_mm];
    superdealloc_mm;
}

@end
